﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetData;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace LBSoft.HplusAdmin.Business.MenuManage
{
    /// <summary>
    /// MenuManage 的摘要说明
    /// </summary>
    public class MenuManage : IHttpHandler
    {
        HttpContext con = null;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        public void ProcessRequest(HttpContext context)
        {
            con = context;

            switch (con.Request["PostType"])
            {
                case "list": LoadList(); break;
                case "get": GetData(); break;
                case "set": SetData(); break;
                case "del": DelData(); break;
            }
        }

        #region 列表
        private void LoadList()
        {
            switch (con.Request["ActionType"])
            {
                case "Menu": LoadMenuList(); break; //菜单列表
                case "RoleMenuButton": LoadRoleMenuButtonList(); break; //系统菜单按钮列表（根据角色）
                case "UserMenuButton": LoadUserMenuBuutonList(); break; //系统菜单按钮列表（根据用户）
            }
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        private void LoadMenuList()
        {
            StringBuilder sqlWhere = new StringBuilder();
            string menuName = con.Request["MenuName"].ToString2();

            if (!string.IsNullOrEmpty(menuName))
            {
                sqlWhere.Append($" and MenuName like '%{menuName}%'");
            }
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT * FROM dbo.SYS_Menu
            WHERE IsDelete=0 AND MenuType=1 {sqlWhere}
            ORDER BY Sort ASC"));

            string strJson = JsonConvert.SerializeObject(dt);
            con.Response.Write(strJson);
        }

        /// <summary>
        /// 系统菜单按钮列表（根据角色）
        /// </summary>
        private void LoadRoleMenuButtonList()
        {
            string roleGUID = con.Request["RoleGUID"];
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder(@"SELECT GUID MenuGUID,ParentId,'0' PageRight, '' ButtonRight, '' ButtonList,MenuName,Sort FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuType=1 ORDER BY Sort ASC"));

            //根据roleid 获取对应页面权限
            DataTable dtPageRight = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT r.MenuGUID FROM dbo.SYS_RoleRight r
            INNER JOIN dbo.SYS_Menu m ON r.MenuGUID=m.GUID
            WHERE m.IsDelete=0 AND m.MenuType=1 AND r.RoleGUID='{roleGUID}'"));

            //根据roleid 获取对应按钮权限
            DataTable dtButtonRight = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT r.MenuGUID,m.ParentId FROM dbo.SYS_RoleRight r
            INNER JOIN dbo.SYS_Menu m ON r.MenuGUID=m.GUID
            WHERE m.IsDelete=0 AND m.MenuType=2 AND r.RoleGUID='{roleGUID}'"));

            //操作按钮
            DataTable dtButtonList = systemidao.GetDataTableBySQL(new StringBuilder(@"SELECT GUID MenuGUID,ParentId,MenuName FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuType=2 ORDER BY Sort ASC"));

            foreach (DataRow dr in dt.Rows)
            {
                string menuGUID = dr["MenuGUID"].ToString();

                DataRow[] drPageRight = dtPageRight.Select($"MenuGUID='{menuGUID}'");
                if (drPageRight != null && drPageRight.Length > 0)
                {
                    dr["PageRight"] = "1";
                }

                DataRow[] drButtonRight = dtButtonRight.Select($"ParentId='{menuGUID}'");
                if (drButtonRight != null && drButtonRight.Length > 0)
                {
                    List<string> rightItems = new List<string>();
                    foreach (DataRow drBR in drButtonRight)
                    {
                        string btMenuGUID = drBR["MenuGUID"].ToString();
                        rightItems.Add(btMenuGUID);
                    }
                    dr["ButtonRight"] = string.Join(",", rightItems);
                }

                DataRow[] drButtonList = dtButtonList.Select($"ParentId='{menuGUID}'");
                if (drButtonList != null && drButtonList.Length > 0)
                {
                    DataTable dtBL = drButtonList.CopyToDataTable();
                    dr["ButtonList"] = JsonConvert.SerializeObject(dtBL);
                }
            }

            string strJson = JsonConvert.SerializeObject(dt);
            con.Response.Write(strJson);
        }

        /// <summary>
        /// 系统菜单按钮列表（根据用户）
        /// </summary>
        private void LoadUserMenuBuutonList()
        {
            string userGUID = con.Request["UserGUID"];
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder(@"SELECT GUID MenuGUID,ParentId,'0' PageRight, '' ButtonRight, '' ButtonList,MenuName,Sort FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuType=1 ORDER BY Sort ASC"));
            
            //根据roleid 获取对应页面权限
            DataTable dtPageRight = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT r.MenuGUID FROM dbo.SYS_UserRight r
            INNER JOIN dbo.SYS_Menu m ON r.MenuGUID=m.GUID
            WHERE m.IsDelete=0 AND m.MenuType=1 AND r.UserGUID='{userGUID}'"));

            //根据roleid 获取对应按钮权限
            DataTable dtButtonRight = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT r.MenuGUID,m.ParentId FROM dbo.SYS_UserRight r
            INNER JOIN dbo.SYS_Menu m ON r.MenuGUID=m.GUID
            WHERE m.IsDelete=0 AND m.MenuType=2 AND r.UserGUID='{userGUID}'"));

            //操作按钮
            DataTable dtButtonList = systemidao.GetDataTableBySQL(new StringBuilder(@"SELECT GUID MenuGUID,ParentId,MenuName FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuType=2 ORDER BY Sort ASC"));

            foreach (DataRow dr in dt.Rows)
            {
                string menuGUID = dr["MenuGUID"].ToString();

                DataRow[] drPageRight = dtPageRight.Select($"MenuGUID='{menuGUID}'");
                if (drPageRight != null && drPageRight.Length > 0)
                {
                    dr["PageRight"] = "1";
                }

                DataRow[] drButtonRight = dtButtonRight.Select($"ParentId='{menuGUID}'");
                if (drButtonRight != null && drButtonRight.Length > 0)
                {
                    List<string> rightItems = new List<string>();
                    foreach (DataRow drBR in drButtonRight)
                    {
                        string btMenuGUID = drBR["MenuGUID"].ToString();
                        rightItems.Add(btMenuGUID);
                    }
                    dr["ButtonRight"] = string.Join(",", rightItems);
                }

                DataRow[] drButtonList = dtButtonList.Select($"ParentId='{menuGUID}'");
                if (drButtonList != null && drButtonList.Length > 0)
                {
                    DataTable dtBL = drButtonList.CopyToDataTable();
                    dr["ButtonList"] = JsonConvert.SerializeObject(dtBL);
                }
            }

            string strJson = JsonConvert.SerializeObject(dt);
            con.Response.Write(strJson);
        }
        #endregion

        #region 获取
        private void GetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Menu": GetMenu(); break; //获取菜单
                case "AllButton": GetAllButton(); break; //获取全部按钮
                case "MenuButton": GetMenuButton(); break; //获取菜单按钮
            }
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        private void GetMenu()
        {
            string guid = con.Request["GUID"].ToString2();

            Hashtable ht = systemidao.GetDataByID("SYS_Menu", "GUID", guid);

            con.Response.Write(JsonConvert.SerializeObject(ht));
        }

        /// <summary>
        /// 获取全部按钮
        /// </summary>
        private void GetAllButton()
        {
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder("SELECT * FROM dbo.SYS_Button WHERE IsDelete=0 ORDER BY Sort ASC"));
            if (dt != null && dt.Rows.Count>0)
            {
                json.success = true;
                json.rows = dt;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 获取菜单按钮
        /// </summary>
        private void GetMenuButton()
        {
            string pid = con.Request["PID"].ToString2();

            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($"SELECT * FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuType=2 AND ParentId='{pid}' ORDER BY Sort asc"));
            if (dt != null && dt.Rows.Count > 0)
            {
                json.success = true;
                json.rows = dt;
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region  编辑
        private void SetData()
        {
            switch (con.Request["ActionType"])
            {
                case "Menu": SetMenu(); break; //菜单保存
                case "AddButton": SetAddButton(); break; //添加菜单按钮
            }
        }

        /// <summary>
        /// 菜单保存
        /// </summary>
        private void SetMenu()
        {
            try
            {
                string userId = RequestSession.GetSessionUser().UserId;
                string userAccount = RequestSession.GetSessionUser().UserAccount;

                string guid = con.Request["GUID"].ToString2();
                string menuName = con.Request["MenuName"].ToString2();

                DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder($@"SELECT GUID FROM dbo.SYS_Menu WHERE IsDelete=0 AND MenuName='{menuName}' AND GUID!='{guid}'"));
                if (dt != null && dt.Rows.Count > 0)
                {
                    json.msg = "菜单名称已存在！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                Hashtable ht = systemidao.AddHashtable("SYS_Menu", con);

                if (string.IsNullOrEmpty(guid))
                {
                    ht["IsDelete"] = 0;
                    ht["CreateDate"] = DateTime.Now;
                    ht["CreateUserId"] = userId;
                    ht["CreateAccount"] = userAccount;
                }
                else
                {
                    ht.Remove("IsDelete");
                    ht.Remove("CreateDate");
                    ht.Remove("CreateUserId");
                    ht.Remove("CreateAccount");
                    ht["ModifyDate"] = DateTime.Now;
                    ht["ModifyUserId"] = userId;
                    ht["ModifyAccount"] = userAccount;
                }

                bool result = systemidao.SubmitData("SYS_Menu", "GUID", guid, ht);
                json.success = result;

                if (result)
                {
                    json.msg = "保存成功！";
                }
                else
                {
                    json.msg = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                json.msg = ex.Message;
                log.WriteExceptionLog(ex);
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }

        /// <summary>
        /// 添加菜单按钮
        /// </summary>
        private void SetAddButton()
        {
            string userId = RequestSession.GetSessionUser().UserId;
            string userAccount = RequestSession.GetSessionUser().UserAccount;

            string pid = con.Request["PID"].ToString2();
            string buttonId = con.Request["ButtonId"].ToString2();

            Hashtable ht = systemidao.GetDataByID("SYS_Button", "GUID", buttonId);
            string buttonName = ht["ButtonName"].ToString2();
            string buttonIcon = ht["ButtonIcon"].ToString2();
            string buttonCode = ht["ButtonCode"].ToString2();
            string buttonType = ht["ButtonType"].ToString2();

            //判断是否已选择按钮
            DataTable dtSelected = systemidao.GetDataTableBySQL(new StringBuilder($"SELECT * FROM dbo.SYS_Menu WHERE ParentId='{pid}' AND MenuName='{buttonName}' AND IsDelete=0 AND MenuType=2"));
            if (dtSelected != null && dtSelected.Rows.Count > 0)
            {
                json.success = false;
                json.msg = "该按钮已存在";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            Hashtable htMenu = new Hashtable();
            htMenu["GUID"] = CommonHelper.GetGuid;
            htMenu["ParentId"] = pid;
            htMenu["MenuName"] = buttonName;
            htMenu["MenuIcon"] = buttonIcon;
            htMenu["MenuType"] = 2;
            htMenu["NavigateUrl"] = buttonCode;
            htMenu["ButtonType"] = buttonType; //增加按钮位置字段， 区分加载
            htMenu["Sort"] = CommonHelper.GetInt(systemidao.ExecuteScalar($"SELECT MAX(Sort) FROM SYS_Menu WHERE ParentId='{pid}' AND IsDelete = 0 AND MenuType=2")) + 1;
            htMenu["IsDelete"] = 0;
            htMenu["CreateDate"] = DateTime.Now;
            htMenu["CreateUserId"] = userId;
            htMenu["CreateAccount"] = userAccount;

            bool returnValue = systemidao.SubmitData("SYS_Menu", "GUID", "", htMenu);
            json.success = returnValue;
            if (returnValue)
            {
                json.msg = "分配成功！";
            }
            else
            {
                json.msg = "分配失败！";
            }
            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 删除
        private void DelData()
        {
            switch (con.Request["ActionType"])
            {
                case "Menu": DelMenu(); break; //菜单删除
            }
        }

        /// <summary>
        /// 菜单删除
        /// </summary>
        private void DelMenu()
        {
            string guid = con.Request["GUID"].ToString2();

            if (string.IsNullOrEmpty(guid))
            {
                json.success = false;
                json.msg = "没有要删除的主键！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            List<string> list = guid.Split(',').ToList<string>();
            bool result = systemidao.BatchUpdateDeleteData("SYS_Menu", "GUID", list.ToArray()) > 0;
            json.success = result;

            if (result)
            {
                json.msg = "删除成功！";
            }
            else
            {
                json.msg = "删除失败！";
            }

            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}